package hu.diploma.android;

import hu.diploma.android.util.ServiceProviderImpl;
import hu.diploma.common.resource.UserResource;
import hu.diploma.common.vos.UserVo;

import org.restlet.resource.ClientResource;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class Registration extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.reg);
		final SharedPreferences settings = getSharedPreferences(ServiceProviderImpl.PREFS_NAME, MODE_PRIVATE);

		final EditText userName = (EditText) findViewById(R.id.reg_login_name);

		final EditText password = (EditText) findViewById(R.id.reg_password);

		final EditText passwordAgain = (EditText) findViewById(R.id.reg_password_again);

		final CheckBox savePasswors = (CheckBox) findViewById(R.id.save_password);

		savePasswors.setChecked(settings.getBoolean("save_password", false));

		Button regButton = (Button) findViewById(R.id.start_reg_button);
		regButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				Boolean result = null;
				String passwordStr = password.getText().toString();
				String passwordAgainStr = passwordAgain.getText().toString();
				String userNameStr = userName.getText().toString();
				if (!passwordStr.equals(passwordAgainStr)) {
					Toast.makeText(Registration.this, R.string.reg_error, Toast.LENGTH_LONG).show();
				} else {

					UserVo user = new UserVo();
					user.setName(userNameStr);
					user.setPassword(passwordStr);

					try {
						ClientResource cr = new ClientResource("http://192.168.1.65:8888/restlet/user");

						UserResource resource = cr.wrap(UserResource.class);

						result = resource.registration(user);

					} catch (Exception e) {
						Toast.makeText(Registration.this, R.string.login_error, Toast.LENGTH_LONG).show();
					}
					if (result != null) {
						if (result) {

							SharedPreferences.Editor editor = settings.edit();
							editor.putString("user_name", userNameStr);

							if (savePasswors.isChecked()) {
								editor.putString("password", passwordStr);
							} else {
								editor.putString("password", null);
							}

							editor.putBoolean("save_password", savePasswors.isChecked());
							editor.commit();

							ServiceProviderImpl.getInstance().setUser(user);

							setResult(RESULT_OK, getIntent());
							finish();

						} else {
							Toast.makeText(Registration.this, R.string.reg_fail, Toast.LENGTH_LONG).show();
						}
					}
				}
			}
		});
	}

}